import path from "path";
import { Sequelize } from "sequelize-typescript";
import  User  from "../models/User"
import { Cfg } from "../common/config";
const USalt = "iotbase"
var shajs = require('sha.js')
const sequelize = new Sequelize(
  Cfg.dbOption.dbname,
  Cfg.dbOption.username,
  Cfg.dbOption.password,
  {
    host: Cfg.dbOption.host,
    port: Cfg.dbOption.port,
    dialect: "postgres",
    //operatorsAliases: undefined,
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 1000,
    },
  }
);
async function addUsr(un:string,pwdSet:string){
  const admin = un
  let auser = await User.findByPk(admin)
  const pwd : string = shajs('sha256').update(pwdSet + USalt).digest('hex')
  if (!auser) {
    let user = new User()
    user.uname = admin
    user.pwd = pwd
    user.roleId = "admin"
    //加盐是为了避免撞库攻击

    console.log("***************", user)
    //let res = User.build(user)
    let res = await user.save()
    console.log("*************", res)
    //User.create({uname:"2"})
  } else if (!auser.pwd) {
    auser.pwd = pwd
    auser.roleId = 'admin'
    const nuser = await auser.save()
    console.log("**********!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*****", nuser)

  }
  console.log("**********!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*****", auser)
}
sequelize
  .authenticate()
  .then(async () => {
    console.log("Connection has been established successfully");
    console.log(
      "-----path-----",
      __dirname,
      path.resolve(__dirname, `../models/`)
    );
    sequelize.addModels([path.resolve(__dirname, `../models/`)]);
    sequelize.sync({
      alter: true
    }).then(async () => {
     addUsr("admin","wsj12345")
     addUsr("IOT2021","Mima2021@)@!")

    })

  })
  .catch((err) => {
    console.log("Unable to connect to the database:", err);
  });

export { sequelize,USalt };
